    import { mapState, mapGetters } from 'vuex';
    import { bus } from '../../assets/js/bus.js';
    import {PDFJS} from 'pdfjs-dist';
    PDFJS.workerSrc ='/static/pdf.worker.min.js';
    import { cookie,disable_scroll,enable_scroll } from '../../utils/utils';
    import $ from 'jquery';
    var dragscroll = require('../../assets/js/dragscroll_micro.js');
    export default{
        data(){
            return{
                q:this.$route.query.q,
                t:this.$route.query.t,
                uploadToken: null,
                filess: [],
                statute:{
                    number:{},
                    about_gold:{},
                    uploads:{},
                },
                downloadUrl:null,
                pdf_url: null,
                pdfDoc: null,
                pageNum: 1,
                totalNum:0,
                pageRendering: false,
                pageNumPending: null,
                dirs: [],
                level:1,
                showDir: false,

                latestStatuteList:[],
                newsList:[],
                evaluation:{
                    list:[],
                    page:1,
                    size:15,
                },
                note:{
                    list:[],
                    page:1,
                    size:15
                },
                message:{
                    list:[],
                    page:1,
                    size:15
                },
                comprehensiveType:1,
                dialogForm:false,
                dialogTitle:'',
                whichForm:0,
                // 提交评价
                formEvaluate: {
                    score: 0,
                    content: '0',
                    statute_id: this.$route.query.q
                },
                // 提交留言
                formMessage: {
                    content: '',
                    statute_id: this.$route.query.q
                },
                // 提交笔记
                formNote: {
                    content: '',
                    statute_id: this.$route.query.q
                },
                // 上传翻译
                upWord:false,
                Chinese:false,
                isPayGold:false,
                totalRata:0,

                loadedMemberStatus:false
            }
        },
        computed: {
            ...mapGetters(['token','member'])
        },
        created(){
            //this.initNews();
            // this.fetchEvaluate();
            // this.fetchMessage();
            this.$nextTick(_=>{
                if(document.body.clientWidth > 992){
                    this.fetchNote();
                    this.fetchStatute();
                    this.init();
                    this.fetchUploadToken();
                    this.getRateAverage();
                    this.initLatestStatute();
                    if(document.referrer.indexOf('statute?') > 0){
                        var referrer = document.referrer;
                        cookie.set('referrer',referrer)
                    }
                    $('.article-wrapper,.chapter,.page').mouseenter(e=>{
                        $('body').addClass('noscroll');
                    }).mouseleave(e=>{
                        $('body').removeClass('noscroll');
                    });
                    this.$refs['articleWrapper'].addEventListener('scroll',e=>{
                        this.listenArticle(e);
                    });
                }
                
                this.isLoadedMember();
                
            })
        },
        watch:{
            member(newValue, oldValue){
                if(newValue){
                    this.fetchNote();
                    this.isPay();
                    this.loadedMemberStatus = true;
                }
            }
        },
        methods:{
            back(){
                if(cookie.get('referrer')){
                    location.href = cookie.get('referrer');
                }
            },
            listenArticle(e){
                let childrenHeight = $('.article-inside').height();
                let parentHeight = $(e.target).height();
                let scrollTop = $(e.target).scrollTop();
                if(childrenHeight <= parentHeight+scrollTop){
                    this.onNextPage();
                }else if(scrollTop == 0){
                    this.onPrevPage();
                }
            },
            getRateAverage(){
                this.$http.get('/getAverage',{
                    params:{
                        statute_id:this.q,
                        fe:1
                    }
                })
                .then(res=>{
                    this.totalRata = res.data;
                })
                .catch(err=>{
                    console.log(err)
                })
            },
            // 获取法规数据
            fetchStatute() {
                this.$http.get('statute/' + this.q,{
                    params:{
                        fe:1,
                        include:'statute,term'
                    }
                }).then(ret => {
                    this.statute = ret.data.data;
                    this.downloadUrl = `${this.statute.english_uploads[0].url}?attname=${this.statute.english_uploads[0].name}`;
                }).catch(err => {
                    this.$Notice.error({ title: '没有找到该法规！'});
                })
            },
            init() {
                let url = 'http://v3.jiathis.com/code/jia.js'
                let script = document.createElement('script')
                script.setAttribute('src', url)
                document.getElementsByTagName('head')[0].appendChild(script)
            },
            initLatestStatute(){
                this.$http.get('/statute/list',{
                    params: {
                        category:'',
                        fe:1,
                        page:1,
                        size:10,
                    }
                }).then(response => {
                    this.latestStatuteList = response.data.data.slice(0,10);
                }).catch(err => {

                })
            },
            initNews(){
                this.$http.get('/news/list',{
                    params: {
                        include:'category',
                        fe:1
                    }
                }).then(response => {
                    var data = response.data;
                    this.newsList = data.data;
                }).catch(err => {

                })
            },
            showDialog(type){
                switch(type){
                    case 1:this.dialogTitle = '评价';break;
                    case 2:this.dialogTitle = '笔记';break;
                    case 3:this.dialogTitle = '留言';break;
                }
                this.whichForm = type;
                this.dialogForm = true;
            },
            close(){
                this.dialogForm = false;
            },
            // 提交评价
            doEvaluate() {
                let data = this.formEvaluate;
                data.include = "member";
                data.fe = 1;
                this.$http.post('evaluate/add', data).then(ret => {
                    this.$Message.success('评论成功！');
                    this.fetchEvaluate();
                    this.dialogForm = false;
                }).catch(err=>{
                    this.$Message.error('评论失败！');
                })
            },
            // 查询评价
            fetchEvaluate() {
                this.evaluatePadding = true;
                if ( this.q != null ) {
                    this.evaluatePadding = false;
                }
                this.$http.get('evaluate/list' , {
                    params: {
                        statute: this.q,
                        include: 'member',
                        page: this.evaluation.page,
                        fe:1
                    }
                }).then(ret => {
                    this.evaluation.list = ret.data.data;
                    this.evaluation.page = ret.data.meta.pagination.current_page;
                    this.evaluation.total = ret.data.meta.pagination.total;
                }).catch(err => {
                })
            },
            save(){
                if(this.member.id){
                    if(this.whichForm == 1){
                        this.doEvaluate();
                    }else if(this.whichForm == 2){
                        this.doNote();
                    }else if(this.whichForm == 3){
                        this.doMessage();
                    }
                }else{
                    this.dialogForm = false;
                    this.$store.dispatch('login',true);
                }

            },
            // 查询笔记
            fetchNote() {
                this.$http.get('note/list' , {
                    params: {
                        member: this.member.id,
                        statute: this.q,
                        len: 1000,
                        fe:1
                    }
                }).then(res => {
                    this.note.list = res.data.data;
                }).catch(err => {

                })
            },
            // 提交笔记
            doNote() {
                if(this.formNote.content){
                    this.formNote.fe = 1;
                    this.$http.post('note/add', this.formNote).then(res => {
                        this.$Message.success('成功');
                        this.dialogForm = false;
                        this.fetchNote();
                    }).catch(err => {

                    })
                }
            },
            // 查询留言
            fetchMessage() {
                this.$http.get('message/list' , {
                        params: {
                            member: this.member.id,
                            statute: this.q,
                            len: 1000,
                            fe:1,
                            include:'member,reply'
                        }
                }).then(res => {
                    this.message.list = res.data.data;
                }).catch(err => {

                })
            },
            // 提交留言
            doMessage() {
                if(this.formMessage.content){
                    var data = this.formMessage;
                    data.fe = 1;
                    this.$http.post('message/add', data).then(res => {
                        this.$Message.success('留言成功');
                        this.fetchMessage();
                        this.dialogForm = false;
                    }).catch(err => {

                    })
                }
            },
            isLoadedMember(){
                if(this.t){
                    let cnt = 0;
                    let interval = setInterval(_=>{
                        if(this.loadedMemberStatus || cnt++ == 10){
                            clearInterval(interval)
                            this.fetchPdf();
                            if(cnt == 11){
                                this.$router.push({path:'/statute-content',query:{q:this.q}});
                                this.t = null;
                            }
                        }
                    },500)
                }
                else{
                    this.fetchPdf();
                }
            },
            fetchPdf() {
                var that = this;
                bus.$on('setPage', (obj) => {
                    if({}.toString.call(obj.dest) === '[object Array]'||{}.toString.call(obj.dest) === '[object Object]'){
                        this.setPage(obj.dest);
                    }else{
                        this.setPageByDest(obj.dest);
                    }

                });
                let data = {};
                data.id = this.q;
                if(this.t && this.member.id){
                    data.back = 2;
                }
                this.$http.get('/getPdf',{
                    params:data
                }).then(res => {
    //                this.$http.get('/getPdf' + '?id=' + this.id).then(ret => {
                        // console.log(ret.data);
    //                    let url = "http://ot2vyou76.bkt.clouddn.com/Fv5PTRt1C2ihBp_otno3-Y2LsMTb";
                    let url = res.data;
    //                    let url = "/static/git.pdf";
    //                    let url = "/static/abc.PDF";
                    if (document.body.clientWidth <= 992) {
                        /* var aLink = document.createElement('a');
                        aLink.href = url;
                        aLink.click(); */
                        console.log(url)
                        window.location.href = url;
                        return false
                    }
                    PDFJS.getDocument(url).then(function (pdfDoc_) {
                        that.pdfDoc = pdfDoc_;
                        that.totalNum=pdfDoc_.numPages;
                        that.renderPage(1);
                        pdfDoc_.getOutline().then(function (outline) {
                            that.dirs = outline;
                            /*if(that.dirs){
                                that.setPageByDest(that.dirs[0].dest);
                            }*/
                            that.showDir = true;
                        });
                    });
                }).catch(err => {
                    console.log(err);
                    this.$Message.info({
                        content: err.response.data.message,
                        duration: 3
                    });
                });
            },
            renderPage(num) {
                var that = this;
                this.pageRendering = true;
                var statuteLeft = document.getElementsByClassName('statute-left')[0];
                // Using promise to fetch the page
                this.pdfDoc.getPage(num).then(function (page) {
                    var viewport = page.getViewport(statuteLeft.clientWidth / page.getViewport(1).width);
                    that.$refs.canvas.width = viewport.width * 2;
                    that.$refs.canvas.height = viewport.height * 2;
                    that.$refs.canvas.style.width = viewport.width + 'px'
                    that.$refs.canvas.style.height = viewport.height + 'px'
                    
                    for(let x = 0; x < viewport.transform.length; x++){
                        viewport.transform[x] = viewport.transform[x] * 2;
                    }
                    var ctx = that.$refs.canvas.getContext('2d');
                    // Render PDF page into canvas context
                    var renderContext = {
                        canvasContext: ctx,
                        viewport: viewport
                    };
                    var renderTask = page.render(renderContext);
                    // Wait for rendering to finish
                    renderTask.promise.then(function () {
                        that.pageRendering = false;
                        if (that.pageNumPending !== null) {
                            // New page rendering is pending
                            that.renderPage(that.pageNumPending);
                            that.pageNumPending = null;
                        }
                    });
                });
            },
            pageScrollToTop(){
                $('.article-wrapper').scrollTop(50);
            },
            queueRenderPage(num) {
                this.pageScrollToTop();
                if (this.pageRendering) {
                    this.pageNumPending = num;
                } else {
                    this.renderPage(num);
                }
            },
            onPrevPage() {
                if (this.pageNum <= 1) {
                    return;
                }
                this.pageNum--;
                this.queueRenderPage(this.pageNum);
            },
            onNextPage() {
                if (this.pageNum >= this.pdfDoc.numPages) {
                    return;
                }
                this.pageNum++;
                this.queueRenderPage(this.pageNum);
            },
            setPageByDest(dest) {
                var that = this;
                this.pdfDoc.getDestination(dest).then(function (obj) {
                    return that.pdfDoc.getPageIndex(obj[0]);
                }).then(function (index) {
                    that.pageNum = index + 1;
                    if (that.pageNum > that.pdfDoc.numPages) {
                        return;
                    }
                    that.queueRenderPage(that.pageNum);
                })
            },
            getName(obj) {
                var that = this;
                if({}.toString.call(obj.dest) === '[object Array]'||{}.toString.call(obj.dest) === '[object Object]'){
                    return obj.dest;
                    this.setPage(obj.dest);
                }else{
                    this.pdfDoc.getDestination(dest).then(function (obj) {
                        return obj;
                    })
                }
            },
            setPage(obj) {
                var that = this;
                this.pdfDoc.getPageIndex(obj[0]).then(function (index) {
                    that.pageNum = index + 1;
                    if (that.pageNum >= that.pdfDoc.numPages) {
                        return;
                    }
                    that.queueRenderPage(that.pageNum);
                });
            },
            showChinese(){
                if(this.t){
                    location.href = '/statute-content?q='+this.q
                }else{
                    //是否登录
                    if(!this.member.id){
                        this.$store.dispatch('login',true);
                    }else{
                        //判断查看中文是否消费金币或者已经购买法规卡
                        if(this.statute.about_gold.read == 0 || this.member.statute){
                            location.href = '/statute-content?q='+this.q+'&t=zh'
                        }else{
                            //提示购买
                            this.$Modal.confirm({
                                title: '提示',
                                content: '查看中文需要购买法规卡。点击“确定”前往个人中心',
                                onOk: () => {
                                    location.href = '/personal?name=card'
                                },
                                onCancel: () => {

                                }
                            });
                        }
                    }
                }
            },
            isPay(){
                this.$http.post('/consumption/statuteRead',{
                    statute_id:this.q,
                    fe:1
                })
                .then(res=>{
                    if(res.data.type == 200){
                        this.isPayGold = true;
                    }
                })
            },
            consume(){
                this.$http.post('/pay/gold', {
                    statute_id:this.q,
                    gold:this.statute.about_gold.read,
                    statute_type:'READ',
                    done:'YES',
                })
                .then(res => {
                    this.$Message.success('支付成功');
                    setTimeout(_=>{
                        location.href = '/statute-content?q='+this.q+'&t=zh';
                    },1500);
                }).catch(err => {
                      if (err.response.data) {
                          this.$Message.error(err.response.data.message);
                      }else {
                          this.$Message.error('未知错误');
                      }
                })
            },
            // 上传翻译
            uploadWord(){
                if(this.member.id){
                    this.upWord = true;
                }else{
                    this.$store.dispatch('login',true);
                }
            },
            // 上传成功
            handleAvatarSuccess(res, file) {
                this.filess = [{ name: file.name, url: this.url + res.key, key: res.key}];
                this.$Message.success('上传成功！');
                this.$http.post('/auditing/add',{
                    statute_id:this.q,
                    uploads:file,
                    member_id:this.member.id
                }).then(res => {
                    this.$Message.success(  "上传成功");
                }).catch(err => {
                    this.$Message.error( '增加数据库失败');
                })
            },
            // 获取上传token
            fetchUploadToken() {
                this.$http.get('upload/get').then(res => {
                    this.uploadToken = {
                        token: res.data.token
                };
                    this.url = res.data.url;
                }).catch(err => {
                    this.$Message.error('查找 上传Token 失败！');
                })
            },
        },
        components: {
            // 局部注册，dire是标签名称
            'dire': {
                name:'dire',
                template:
                `<ul class="catalogue">
                    <li v-for="(item, index) in dir" style="line-height:29px;vertical-align:middle;border-bottom: solid #888 1px;">
                        <a :title="item.title" style="display:block;" v-on:click="setPage(item)" class="ellipsis">
                            <span v-html="space"></span>{{item.title}}
                        </a>
                        <dire v-if="hasSub" :level="level+1" :dir="item.items" ></dire>
                    </li>
                </ul>`,
                props: ['dir','level'],
                mounted(){

                },
                methods: {
                    setPage(obj) {
                        bus.$emit('setPage',obj);
                    },
                    getName(obj){
                        bus.$emit('getName',obj);
                    }
                },
                computed: {
                    space:function(){
                        var space = '';
                        for(let i=0;i<this.level;i++){
                            space+="&emsp;";
                        }
                      return space;
                    },
                    hasSub: function () {
                        return this.dir.length>0;
                    }
                },
            }
        }
    }